package com.example.computer_component_manager.volley

import android.app.Application
import android.content.SharedPreferences
import com.android.volley.RequestQueue
import com.android.volley.toolbox.Volley

/**
 * Volley声明周期由本类掌握
 *
 * @author 1923111015董寺卓
 */

class VolleyApplication : Application() {

    companion object {

        private const val SET_COOKIE_KEY = "Set-Cookie"
        private const val COOKIE_KEY = "Cookie"
        private const val SESSION_COOKIE = "JSESSIONID"
        lateinit var instance: VolleyApplication

    }

    lateinit var requestQueue: RequestQueue
    lateinit var sharedPreferences: SharedPreferences


    override fun onCreate() {
        super.onCreate()
        instance = this
        sharedPreferences = getSharedPreferences("mySessionId", MODE_PRIVATE)
        requestQueue = Volley.newRequestQueue(this)
    }

    /**
     * 检查返回的Response header有无session
     *
     * @param responseHeaders 响应头
     */
    fun checkSessionCookie(responseHeaders: Map<String, String>) {
        if (responseHeaders.containsKey(SET_COOKIE_KEY) && responseHeaders[SET_COOKIE_KEY]
            !!.startsWith(SESSION_COOKIE)
        ) {
            var cookie: String = responseHeaders[SET_COOKIE_KEY]!!
            if (cookie.isNotEmpty()) {
                val splitCookie = cookie.split(";")
                val splitSessionId = splitCookie[0].split("=")
                cookie = splitSessionId[1]
                val prefEditor = sharedPreferences.edit()
                prefEditor.putString(SESSION_COOKIE, cookie)
                prefEditor.apply()
            }
        }
    }

    /**
     * 添加session到Request header中
     */
    fun addSessionCookie(requestHeaders: MutableMap<String, String>): MutableMap<String, String> {
        val sessionId = sharedPreferences.getString(SESSION_COOKIE, "")
        val map = HashMap<String, String>()
        if (sessionId != null && sessionId.isNotEmpty()) {
            val builder = StringBuilder().append("$SESSION_COOKIE=$sessionId")
            if (requestHeaders.containsKey(COOKIE_KEY)) {
                builder.append("; ${requestHeaders[COOKIE_KEY]}")
            }
            map[COOKIE_KEY] = builder.toString()
        }
        return map
    }
}
